package com.atguigu.controller;

import com.atguigu.common.constant.MessageConstant;
import com.atguigu.common.constant.RedisMessageConstant;
import com.atguigu.common.entity.Result;
import com.atguigu.common.utils.MySMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.UUID;

@RestController
@RequestMapping("/validateCode")
public class SmsController {

    @Autowired
    JedisPool jedisPool;
    /*
    发送预约短信
     */
    @GetMapping("/sms")
    public Result senSms(@RequestParam("telephone")String phone){
        if (phone==null){
            return new Result(false,"请输入手机号!");
        }
        //先从redis中获取验证码
        Jedis jedis = jedisPool.getResource();
        String redisCode = jedis.get(RedisMessageConstant.SENDTYPE_ORDER+phone);
        //防止接口重刷
        if (!StringUtils.isEmpty(redisCode)){
            Long s = Long.valueOf(redisCode.split("_")[0]);
            long millis = System.currentTimeMillis();
            if (millis-s<60000){ //是否超过1分钟
                return new Result(false,"验证码频率太高，请稍后重试");
            }
        }
        //生成随机6位数子
        String code = UUID.randomUUID().toString().substring(0, 6);
        //保存到redis中
        String s = RedisMessageConstant.SENDTYPE_ORDER +":"+ phone;
        jedis.setex(s,60000,code+"_"+System.currentTimeMillis());
        //发送验证码
        MySMSUtils.sms(phone,code,10);
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    //发送登录短信
    @GetMapping("/send4Login")
    public Result sendCode(@RequestParam("telephone")String telephone){
        Jedis jedis = jedisPool.getResource();
        //随机生成6位数 验证码
        String code = UUID.randomUUID().toString().substring(0, 6);
        String redisCode = jedis.get(RedisMessageConstant.SENDTYPE_LOGIN +":"+ telephone);
        if (redisCode!=null){
            return new Result(false, "不要重复发送验证码");
        }
        //放入redis缓存中
        jedis.setex(RedisMessageConstant.SENDTYPE_LOGIN +":"+ telephone,60*60*24,code);
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
